<template>
  <!---搜索表单-->
  <div class="search-div">
    <el-form label-width="70px" size="small">
      <el-row>
        <el-col :span="12">
          <el-form-item label="关键字">
            <el-input
              style="width: 100%"
              placeholder="用户名"
              v-model="queryDto.userName"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="createTimes"
              type="daterange"
              range-separator="To"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="display:flex">
        <el-button type="primary" size="small" @click="searchUser">
          搜索
        </el-button>
        <el-button size="small" @click="resetData">重置</el-button>
      </el-row>
    </el-form>
  </div>

  <!--添加按钮-->
  <div class="tools-div">
    <el-button type="success" size="small" @click="addShow">添 加</el-button>
  </div>
  <!-- 添加表单 -->
  <el-dialog v-model="dialogVisible" :title="title" width="40%">
    <el-form label-width="120px">
      <el-form-item label="用户名">
        <el-input v-model="sysUser.userName" />
      </el-form-item>
      <el-form-item v-if="sysUser.id == null" label="密码">
        <el-input type="password" show-password v-model="sysUser.password" />
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="sysUser.name" />
      </el-form-item>
      <el-form-item label="手机">
        <el-input v-model="sysUser.phone" />
      </el-form-item>
      <!-- 文件上传 -->
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8200/api/minio/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :headers="headers"
        >
          <img v-if="sysUser.avatar" :src="sysUser.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="sysUser.description" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!---数据展示表格-->
  <el-table :data="list" style="width: 100%" stripe="true">
    <el-table-column prop="userName" label="用户名" />
    <el-table-column prop="name" label="姓名" />
    <el-table-column prop="phone" label="手机" />
    <el-table-column prop="avatar" label="头像" #default="scope">
      <img :src="scope.row.avatar" width="50" />
    </el-table-column>
    <el-table-column prop="description" label="描述" />
    <el-table-column prop="status" label="状态" #default="scope">
      {{ scope.row.status == 1 ? '正常' : '停用' }}
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间" />
    <el-table-column label="操作" #default="scope" align="center" width="280">
      <el-button type="primary" size="small" @click="updateShow(scope.row)">
        修改
      </el-button>
      <el-button type="danger" size="small" @click="removeUser(scope.row)">
        删除
      </el-button>
      <el-button
        type="warning"
        size="small"
        @click="showAssignRoleDialog(scope.row)"
      >
        分配角色
      </el-button>
    </el-table-column>
  </el-table>

  <!-- 分配角色表单 -->
  <el-dialog v-model="dialogRoleVisible" title="分配角色" width="40%">
    <el-form label-width="80px">
      <el-form-item label="用户名">
        <el-input disabled :value="sysUser.userName"></el-input>
      </el-form-item>

      <el-form-item label="角色列表"> 
        <!-- 这是一个复选框组组件，通过v-model绑定了名为roleMap的数据，用于获取和设置用户选择的角色情况-->
        <el-checkbox-group v-model="roleMap">
          <!--el-checkbox（复选框组件）的结构，通过v-for指令遍历allRoles数组（这个数组应该存放了所有可供选择的角色相关信息的对象集合），为每个角色生成一个复选框。每个复选框通过:key绑定了角色的id（这是为了在列表渲染时方便 Vue 进行高效的 DOM 更新等操作），同时:label也绑定了角色的id，用于标识该复选框对应的角色-->
          <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id">
            {{ role.roleName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="saveAssignRole">提交</el-button>
        <el-button @click="dialogRoleVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 分页页码 -->
  <el-pagination
    v-model:current-page="pageParams.page"
    v-model:page-sizes="pageParams.limit"
    :page-sizes="[10, 20, 50, 100]"
    layout="total, sizes, prev, pager, next"
    :total="total"
  />
</template>

<script setup>
import { onMounted, ref } from 'vue'
import {
  getPageApI,
  postUserAPI,
  putUserAPI,
  deleteUserAPI,
  postSaveAssignRoleAPI,
} from '@/api/user'
import { getRoleAllAPI } from '@/api/role'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useApp } from '@/pinia/modules/app'
////////////////////////////////////////////////////////////////////////////////////////分页查询

//分页总数据条数
const total = ref(0)

// 表格数据模型
const list = ref([])

//添加表单的标题
const title = ref('')

//时间的数据模型
const createTimes = ref([])

//分页当前页和每页记录数数据
const pageParamsForm = {
  page: 1, // 页码
  limit: 10, // 每页记录数
}
const pageParams = ref(pageParamsForm)

// 定义搜索表单的数据模型
const queryDto = ref({
  userName: '',
  createTimeBegin: '',
  createTimeEnd: '',
})
// onMounted钩子函数,页面加载完毕发起请求
onMounted(() => {
  getPageData()
})

//////搜索按钮事件,未实现
const searchUser = () => {
  getPageData()
}
///////////////重置按钮事件
const resetData = () => {
  queryDto.value = {}
  createTimes.value = []
  getPageData()
}
//调用后端接口api
const getPageData = async () => {
  if (createTimes.value.length == 2) {
    queryDto.value.createTimeBegin = createTimes.value[0]
    queryDto.value.createTimeEnd = createTimes.value[1]
  }
  const { code, data, message } = await getPageApI(
    pageParams.value.page,
    pageParams.value.limit,
    queryDto.value
  )
  list.value = data.list
  total.value = data.total
}
//////////////////////////////////////////////////////////////////////////添加
//定义数据控制添加表单的显示
const dialogVisible = ref(false)
//添加表单数据模型
const sysUser = ref({
  id: '',
  userName: '',
  name: '',
  phone: '',
  password: '',
  description: '',
  avatar: '',
})

//控制添加表单显示
const addShow = () => {
  //表单标题
  title.value = '添加用户'
  dialogVisible.value = true
  sysUser.value = {}
}
//调佣后端接口
const submit = async () => {
  if (!sysUser.value.id) {
    const { code, data, message } = await postUserAPI(sysUser.value)
    if (code === 200) {
      dialogVisible.value = false
      ElMessage.success('添加用户成功!')
      getPageData()
    }
  } else {
    const { code, data } = await putUserAPI(sysUser.value)
    if (code === 200) {
      dialogVisible.value = false
      ElMessage.success('修改用户成功！')
      getPageData()
    }
  }
}
///////////////////////////////////////////////////////////////////////////////文件上传
// 从pinia中获取token，在进行文件上传的时候将token设置到请求头中
const headers = {
  token: useApp().authorization.token,
}

// 图像上传成功以后的事件处理函数
const handleAvatarSuccess = (response, uploadFile) => {
  sysUser.value.avatar = response.data
}
///////////////////////////////////////////////////////////////////////////////////修改
const updateShow = row => {
  title.value = '修改用户'
  sysUser.value = { ...row }
  dialogVisible.value = true
}
//////////////////////////////////////////////////////////////////////////删除
//调用后台接口
const removeUser = row => {
  ElMessageBox.confirm('是否确定删除?', 'warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const { code } = await deleteUserAPI(row.id)
    if (code === 200) {
      ElMessage.success('删除成功!')
      pageParams.value.page = 1
      getPageData()
    }
  })
}

///////////////////////////////////////////////////////////////////////////////分配角色
const dialogRoleVisible = ref(false)
//角色列表,roleMap这是与后台约定好的键名
const roleMap = ref([])
const allRoles = ref([
  { id: 1, roleName: '管理员' },
  { id: 2, roleName: '业务人员' },
  { id: 3, roleName: '商品录入员' },
])
//分配角色按钮事件,调用后台查询所有角色接口
const showAssignRoleDialog = async row => {
  dialogRoleVisible.value = true
  sysUser.value = { ...row }
  const { code, data } = await getRoleAllAPI(sysUser.value.id)
  allRoles.value = data.roleMap
  roleMap.value = data.assignUserRoleIdList
}
///////////////////////////////////////////保存分配角色

const saveAssignRole = async () => {
  const assignRoleVo = {
    userId: sysUser.value.id,
    roleIdList: roleMap.value,
  }
  const { code, data } = await postSaveAssignRoleAPI(assignRoleVo)
  if (code === 200) {
    ElMessage.success('分配角色成功!')
    dialogRoleVisible.value = false
    getPageData()
  }
}
</script>

<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
